package com.example.litehdfs.util;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.example.litehdfs.config.CodeConstant;
import com.example.litehdfs.model.dto.AdminLoginInfo;
import com.example.litehdfs.model.dto.UserLoginInfo;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class UserCacheUtil {

	@Autowired
	private RedisUtils redisUtils;

	/**
	 * 存入用户缓存
	 * @param key
	 * @param value
	 * @param time 单位s
	 */
	public void putUserInfo(String key, Object value,long time) {
		redisUtils.set(key, value,time, TimeUnit.SECONDS);
	}

	/**
	 * 取出用户缓存
	 * @param key
	 * @return
	 */
	public Object getUserInfo(String key) {
		Object value = redisUtils.get(key);
		return value;
	}

	/**
	 * 移除用户缓存
	 * @param key
	 */
	public void removeUserInfo(String key) {
		redisUtils.del(key);
	}

	/**
	 * 获取当前用户管理员id
	 * 
	 * @return
	 */
	public Long getAdminId() {
		String token = getToken();
		if (StringUtil.isBlank(token)) {
			return null;
		}
		AdminLoginInfo value = (AdminLoginInfo) redisUtils.get(CodeConstant.ADMIN_LOGIN_TOKEN + token);
		if (value != null) {
			return value.getId();
		}
		return null;
	}
	
	public AdminLoginInfo getAdminInfo() {
		String token = getToken();
		if (StringUtil.isBlank(token)) {
			return null;
		}
		AdminLoginInfo value = (AdminLoginInfo) redisUtils.get(CodeConstant.ADMIN_LOGIN_TOKEN + token);
		return value;
	}
	/**
	 * 获取当前用户id
	 * 
	 * @return
	 */
	public Long getUserId() {
		String token = getToken();
		if (StringUtil.isBlank(token)) {
			return null;
		}
		UserLoginInfo value = (UserLoginInfo) redisUtils.get(CodeConstant.USER_LOGIN_TOKEN + token);
		if (value != null) {
			return value.getId();
		}
		return null;
	}
	
	public UserLoginInfo getUserInfo() {
		String token = getToken();
		if (StringUtil.isBlank(token)) {
			return null;
		}
		UserLoginInfo value = (UserLoginInfo) redisUtils.get(CodeConstant.USER_LOGIN_TOKEN + token);
		return value;
	}
	
	
	private String getToken() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = servletRequestAttributes.getRequest();
		
		String token = request.getHeader("Token");
		if (StringUtil.isBlank(token)) {
			token = request.getParameter("token");
		}
		return token;
	}
	
	

}
